$(function(){

    var isEdit = Number(getParamsByUrl(location.href,'isEdit'));
    if(isEdit){
        if(localStorage.getItem("editAddress")){
            var addresses = JSON.parse(localStorage.getItem("editAddress"))
        }
        var html = template("editTpl",addresses);
        $("#editForm").html(html);
    }else{
        var html = template("editTpl",{});
        $("#editForm").html(html);
    }

    var picker = new mui.PopPicker({layer:3});
        picker.setData(cityData);
    $("#selectCity").on("tap",function(){
        picker.show(function(selectItems){
            $('#selectCity').val(selectItems[0].text + 
                selectItems[1].text +
                selectItems[2].text)
        });
    });

    $("#confirm-btn").on("tap",function(){
        var username = $.trim($("[name='username']").val());
        var postCode = $.trim($("[name='postCode']").val());
        var city = $.trim($("[name='city']").val());
        var detail = $.trim($("[name='detail']").val());

        if(!username){
            mui.toast("请输入收货人姓名");
            return;
        }
        if(!postCode){
            mui.toast("请输入邮政编码");
            return;
        }
        if(!detail){
            mui.toast("请输入详细地址");
            return;
        }

        var data = {
            address : city,
            addressDetail : detail,
            recipients : username,
            postcode : postCode
        }

        if(isEdit){
            var url="/address/updateAddress";
            data.id = addresses.id;
        }else{
            var url="/address/addAddress";
        }

        $.ajax({
            type: "post",
            url: url,
            data: data,
            success: function (res) {
                if(res.success){
                   if(isEdit){
                    mui.toast("修改成功");
                   }else{
                    mui.toast("添加成功");  
                   }
                    setTimeout(function(){
                        location.href = "address.html";
                    },2000);
                }else{
                    mui.toast("添加失败");
                }
            }
        });
    });

    

});